import axios from 'axios'
let baseURL
if (process.env.NODE_ENV == 'development') {
    baseURL = '/api';
} else if (process.env.NODE_ENV == 'production') {
    baseURL = '/api'
}

const instance = axios.create({
    baseURL: baseURL,
    timeout: 2000,
    withCredentials: true,
    responseType: 'json',
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    }
})

// 添加请求拦截器，在发送请求之前添加请求头
instance.interceptors.request.use(
    config => {
        config.data = JSON.stringify(config.data);
        //   if (store.state.setToken || localStorage.getItem('TOKEN')) {
        //     config.headers['x-auth-token'] = store.state.setToken || localStorage.getItem('TOKEN');
        //   }
        //   if (store.state.authorization || localStorage.getItem('authorization')) {
        //     config.headers['Authorization'] = store.state.setTokauthorizationen || localStorage.getItem('authorization');
        //   }
        return config;
    },
    error => {
        // iView.LoadingBar.error();
        return Promise.reject(error);
    }
);

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // let xAuthToken = response.headers['x-auth-token'];
    if (response.data.code == '4000' || response.data.code == '3000') {
        return Promise.resolve(response.data);
    }
    if (response.data.code == '202' || response.data.code == '201') {

        return Promise.resolve(response.data);
    }
    return Promise.resolve(response.data)
}, function (err) {
    console.log(err)
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                err.message = 'Bad request';
                break;
            case 401:
                localStorage.removeItem('TOKEN');
                err.message = '未授权，请重新登录';
                break;
            case 403:
                err.message = 'Access Denied';
                break;
            case 404:
                err.message = 'Request error, the resource not found';
                break;
            case 405:
                err.message = 'Request method not allowed';
                break;
            case 408:
                err.message = 'Request timed out';
                // location.reload()
                break;
            case 500:
                err.message = 'Server error';
                break;
            case 501:
                err.message = 'Network not implemented';
                break;
            case 502:
                err.message = 'Network Error';
                break;
            case 503:
                err.message = 'Service is not available';
                break;
            case 504:
                err.message = 'Network timeout';
                // location.reload()
                break;
            case 505:
                err.message = 'http版本不支持该请求';
                break;
            default:
                err.message = `connect error ${err.response.status}`;
        }
    } else {
        err.message = 'Failed to connect to server';
    }
    return Promise.reject(err)
})

// 返回失败提示
function errorState (response) {
    // iView.LoadingBar.finish();
    if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
        return response
    }
}
// 返回成功提示
function successState (res) {
    // iView.LoadingBar.finish();
    return res
}

function apiAxios (method, url, params, ischeck = false, isadd = false) {
    console.log(isadd)
    let urls
    if (isadd) {
        urls = url + '/' + params
    } else {
        urls = url
    }
    console.log(urls)
    let httpDefault = {
        method: method,
        url: urls,
        timeout: 10000
    }

    if (!ischeck && (method == 'GET' || method == 'DELETE')) {
        httpDefault.params = method === 'GET' || method === 'DELETE' ? params : null
    }
    if (!ischeck && (method == 'POST' || method === 'PUT')) {
        httpDefault.params = method === 'POST' || method === 'PUT' ? params : null
    }
    if (ischeck) {
        httpDefault.data = method === 'POST' || method === 'PUT' ? params : null
    }
    return new Promise((resolve, reject) => {
        instance(httpDefault).then(res => {
            successState(res)
            resolve(res)
        }).catch(error => {
            errorState(error)
            reject(error)
        })
    })
}

export default {
    install: function (Vue) {
        Vue.prototype.host = baseURL
        Vue.prototype.getHttp = (url, params, ischeck, isadd) => apiAxios('GET', url, params, ischeck, isadd)
        Vue.prototype.postHttp = (url, params, ischeck) => apiAxios('POST', url, params, ischeck)
    }
}